package si.yun.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import si.yun.entity.SyLoginRecord;
import si.yun.entity.SyUser;
import si.yun.entity.User;
import si.yun.service.LoginService;
import si.yun.utils.JsonData;
import si.yun.utils.Md5Utils;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName LoginWeb
 * @Author SXM
 * @Date 2021/07/28 14:09
 * @Version 1.0
 */
@RestController
@RequestMapping("/login")
@PropertySource({"config.properties"})
public class LoginWeb {
    @Autowired
    private LoginService service;

    /*图片上传路径*/
    @Value("${importbackUserImgpath}")
    private String path;
    /*图片路径*/
    @Value("${backUserImgpath}")
    private String path2;

    /*
     * @Author SXM
     * @Description //用户登录
     * @return si.yun.utils.JsonData
     * @Date 2021/7/28  19:15
     **/
    @PostMapping("/selUser")
    private JsonData selUser(String userName, String passWord,String ip, String cName,HttpSession session){
        //设置会话的生命周期
        //session.setMaxInactiveInterval(100);
        String passWordstr=Md5Utils.md5(passWord);
        SyUser user=service.selUser(userName,passWordstr,ip,cName);
        if(user!=null) {
            if(user.getAvatarUrl()!=null){
                user.setAvatarUrl(path2+user.getAvatarUrl());
            }
            session.setAttribute("user", user);
            return JsonData.buildSuccess(user);
        }
        return JsonData.buildError("登录失败");
    }

    /*
     * @Author SXM
     * @Description //获取登录用户信息
     * @return si.yun.utils.JsonData
     * @Date 2021/7/29  17:04
     **/
    @PostMapping("/selUserContent")
    private JsonData selUserContent(HttpSession session){
        SyUser user=(SyUser) session.getAttribute("user");
        return user!=null?JsonData.buildSuccess(user):JsonData.buildError("服务器错误");
    }

    /*
     * @Author SXM
     * @Description //图片上传
     * @return si.yun.utils.JsonData
     * @Date 2021/8/2  9:24
     **/
    @PostMapping("/updimg")
    public JsonData updimg(HttpServletResponse response, HttpSession session, MultipartFile file, int id) throws IOException {
        if(id>0){
            String newname = upFileImg(file);
            //提交到数据库
            int num=service.updUserImg(id,newname);
            return num>0?JsonData.buildSuccess(newname): JsonData.buildError("上传失败");
        }else{
            return JsonData.buildError("上传失败");
        }
    }

    /*
     * @Author SXM
     * @Description //上传文件
     * @return java.lang.String
     * @Date 2021/8/30  17:45
     **/
    public String upFileImg(MultipartFile file)throws IOException{
        //判断是否存在该文件夹
        File file1=new File(path);
        if(file1.isDirectory()) {
            file1.mkdirs();
        }
        //重命名文件
        long currTime=System.currentTimeMillis();
        String fileName=file.getOriginalFilename();
        String filesub=fileName.substring(fileName.lastIndexOf("."));
        String newName=fileName.substring(0,fileName.lastIndexOf("."))+"_"+currTime+filesub;

        //拼接最终路径
        String route=path+newName;
        //上传
        file.transferTo(new File(route));
        return newName;
    }

    /*
     * @Author SXM
     * @Description //密码md5编辑
     * @return si.yun.utils.JsonData
     * @Date 2021/8/28  10:49
     **/
    @PostMapping("/selMD5pwd")
    public JsonData selMD5pwd(String pwd){
        return JsonData.buildSuccess(Md5Utils.md5(pwd));
    }

    /*
     * @Author SXM
     * @Description //账户设置
     * @return si.yun.utils.JsonData
     * @Date 2021/7/29  15:32
     **/
    @PostMapping("/updUser")
    private JsonData updUser(User user){
        user.setNpwd(Md5Utils.md5(user.getNpwd()));
        int num=service.updUser(user);
        return num>0?JsonData.buildSuccess(num):JsonData.buildError("更新失败");
    }


    /*
     * @Author SXM
     * @Description //发送短信验证码
     * @return
     * @Date 2021/8/1  19:07
     **/
    @Autowired
    public JavaMailSender mailSender;
    @PostMapping("/selmail")//
    public JsonData selmail(String toemail){
        //随机生成的验证码
        long random = Math.round(Math.random() * 1000000);
        //System.out.println("随机生成的验证码"+random);
        String fromemail="2459530653@qq.com";//后期改为官方邮箱
        if(toemail!=""){
            //新建邮箱对象
            SimpleMailMessage sm=new SimpleMailMessage();
            //设置值---发件人
            sm.setFrom(fromemail);
            //收件人
            sm.setTo(toemail);
            //邮件标题
            sm.setSubject("思云课堂验证信息");
            //邮件内容
            sm.setText("您好，您的验证码为"+random);
            //发送邮件
            mailSender.send(sm);
        }
        return JsonData.buildSuccess(random);
    };


    /*
     * @Author SXM
     * @Description //查询登录日志
     * @return si.yun.utils.JsonData
     * @Date 2021/7/30  14:22
     **/
   @GetMapping("/selUserLog")
    public JsonData selUserLog(Integer uId){
       List<SyLoginRecord> listlog=service.selUserLog(uId);
       return listlog!=null?JsonData.buildSuccess(listlog):JsonData.buildError("服务器错误");
   }
}
